using Serilog;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Consul;
using Prometheus;

var builder = WebApplication.CreateBuilder(args);

// 配置Serilog
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.File("logs/gateway-.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

builder.Host.UseSerilog();

// 添加服务到容器
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 添加Ocelot
builder.Services.AddOcelot();

// 添加Consul
builder.Services.AddSingleton<IConsulClient>(sp =>
{
    var consulHost = builder.Configuration.GetValue<string>("Consul:Host") ?? "localhost";
    var consulPort = builder.Configuration.GetValue<int>("Consul:Port", 8500);
    return new ConsulClient(c => c.Address = new Uri($"http://{consulHost}:{consulPort}"));
});

var app = builder.Build();

// 配置HTTP请求管道
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();

// 启用Prometheus指标端点
app.UseMetricServer();
app.UseHttpMetrics();

// 健康检查
app.MapGet("/health", () => Results.Ok(new { Status = "Healthy", Service = "Gateway" }));

// 使用Ocelot
await app.UseOcelot();

app.MapControllers();

Log.Information("Gateway 启动完成");

app.Run(); 